﻿Imports System.Text.RegularExpressions

Public Class FormFusion

    Public Modele As String = "$0"
    Public sResultGlobal As String = ""

    Private Sub RadioButtonRegEx_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButtonRegEx.CheckedChanged
        Me.TextBoxRegEx.Enabled = Me.RadioButtonRegEx.Checked
        Call AjusteModeles()
    End Sub

    Private Sub AjusteModeles()
        Me.ComboBoxModele.Items.Clear()
        Me.ComboBoxModele.Text = ""
        Me.RichTextBox1.Text = ""
        If Me.RadioButtonTexte.Checked Then
            For Each oItem As ListViewItem In Form1.ListViewMarqueurs.CheckedItems
                Me.ComboBoxModele.Items.Add(oItem.Text)
            Next
            If Me.ComboBoxModele.Items.Count > 0 Then Me.ComboBoxModele.Text = Me.ComboBoxModele.Items(0)
        ElseIf Me.RadioButtonRegEx.Checked Then
            Me.ComboBoxModele.Items.Add("Expression régulière")
            Me.RichTextBox1.Text = Me.Modele
            Me.ComboBoxModele.Text = "Expression régulière"
        End If
    End Sub

    Public Function Fusionner() As String
        'Preparer la collection des documents à traiter
        Dim ColDocs As New Collection
        If Me.RadioButtonCourant.Checked Then
            'Document courant
            ColDocs.Add(Form1.DocumentCourant)
        Else
            'Tous les documents
            For Each oItem As ListViewItem In Form1.ListViewFichiers.Items
                ColDocs.Add(oItem.Tag)
            Next
        End If
        'Préparer la collection des expressions régulières a utiliser
        Dim ColMarqueurs As New Collection
        If Me.RadioButtonTexte.Checked Then
            'Récupérer les marqueurs actifs
            For Each oItem As ListViewItem In Form1.ListViewMarqueurs.CheckedItems
                ColMarqueurs.Add(oItem.Tag)
            Next
        ElseIf Me.RadioButtonRegEx.Checked Then
            'Expression régulière définie dans le dialogue
            Dim oMarqueur As New ClassMarqueur
            oMarqueur.Titre = "RegEx"
            oMarqueur.sMasque = Me.TextBoxRegEx.Text
            oMarqueur.Modele = Me.Modele
            ColMarqueurs.Add(oMarqueur)
         End If
        'Affichage
        'Preparer le rapport
        sResultGlobal = ""
        Dim sResultDoc As String = ""
        Dim bAjouter As Boolean
        'Boucler sur tous les documents sélectionné
        Dim iIndexOcc As Long = 0
        Dim DejaVu As New System.Collections.Specialized.StringCollection
        For Each oDoc As ClassDocument In ColDocs
            If Form1.ToolStripProgressBar1.Visible Then Form1.ToolStripProgressBar1.Value += 1
            If oDoc.Contenu <> "" Then
                sResultDoc = ""
                'Entete pour les regroupements par source
                If Me.CheckBoxGrouper.Checked Then
                    sResultGlobal &= vbCrLf & oDoc.Titre
                    If oDoc.Chemin <> "" Then sResultGlobal &= " (" & System.IO.Path.GetDirectoryName(oDoc.Chemin) & ")"
                End If
                'Extraction des informations dans une liste triée par position
                Dim Liste As New System.Collections.SortedList
                For Each oMarqueur As ClassMarqueur In ColMarqueurs
                    Dim oOption As RegexOptions = RegexOptions.Multiline
                    If oMarqueur.SensibleCasse = Boolean.FalseString Then oOption = oOption Or RegexOptions.IgnoreCase
                    Dim oRegEx As New Regex(oMarqueur.Masque, oOption)
                    For Each oMatch As Match In oRegEx.Matches(oDoc.Contenu)
                        iIndexOcc += 1
                        'Ajoute le resultat selon le format choisi
                        If Me.RadioButtonMatchs.Checked Then
                            'Matchs complets, un par ligne
                            bAjouter = True
                            If Me.CheckBoxDoublons.Checked Then bAjouter = Not DejaVu.Contains(oMatch.Value)
                            If bAjouter Then
                                DejaVu.Add(oMatch.Value)
                                Liste.Add(oMatch.Index.ToString("00000000") & " " & oMatch.Value, oMatch.Value)
                            End If
                        ElseIf Me.RadioButtonSubMatchLignes.Checked Then
                            'SubMatch, un par ligne
                            For iIndex As Integer = 1 To oMatch.Groups.Count - 1
                                bAjouter = True
                                Dim sVal = oMatch.Groups(iIndex).Value
                                If Me.CheckBoxDoublons.Checked Then bAjouter = Not DejaVu.Contains(sVal)
                                If bAjouter Then
                                    DejaVu.Add(sVal)
                                    Liste.Add(oMatch.Groups(iIndex).Index.ToString("00000000") & " " & sVal, sVal)
                                End If
                            Next
                        ElseIf Me.RadioButtonSubMatchCol.Checked Then
                            'SubMatch, en colonnes sur une même ligne
                            Dim sSubMatch As String = ""
                            For iIndex As Integer = 1 To oMatch.Groups.Count - 1
                                If sSubMatch <> "" Then sSubMatch &= " | "
                                sSubMatch &= oMatch.Groups(iIndex).Value
                            Next
                            bAjouter = True
                            If Me.CheckBoxDoublons.Checked Then bAjouter = Not DejaVu.Contains(sSubMatch)
                            If bAjouter Then
                                DejaVu.Add(sSubMatch)
                                Liste.Add(oMatch.Index.ToString("00000000") & " " & sSubMatch, sSubMatch)
                            End If
                        ElseIf Me.RadioButtonModele.Checked Then
                            'Formaté, par modèle
                            'If ComboBoxModele.Text = oMarqueur.Titre Then
                            Dim sFormate As String = oMarqueur.Modele
                            'Variables
                            sFormate = Regex.Replace(sFormate, "\$Fichier", oDoc.Titre, RegexOptions.IgnoreCase)
                            sFormate = Regex.Replace(sFormate, "\$Chemin", oDoc.Chemin, RegexOptions.IgnoreCase)
                            sFormate = Regex.Replace(sFormate, "\$No", iIndexOcc.ToString("0"), RegexOptions.IgnoreCase)
                            For iSubMatch As Integer = 0 To oMatch.Groups.Count - 1
                                sFormate = sFormate.Replace("$" & iSubMatch.ToString("0"), oMatch.Groups(iSubMatch).Value)
                            Next
                            bAjouter = True
                            If Me.CheckBoxDoublons.Checked Then bAjouter = Not DejaVu.Contains(sFormate)
                            If bAjouter Then
                                DejaVu.Add(sFormate)
                                Liste.Add(oMatch.Index.ToString("00000000") & " " & sFormate, sFormate)
                            End If
                            'End If
                        Else
                            'Tout le texte
                            bAjouter = True
                            If Me.CheckBoxDoublons.Checked Then bAjouter = Not DejaVu.Contains(oMatch.Value)
                            If bAjouter Then
                                DejaVu.Add(oMatch.Value)
                                Liste.Add(oMatch.Index.ToString("00000000") & " " & oMatch.Value, oMatch.Value)
                            End If
                        End If
                    Next 'oMatch
                Next 'RegEx
                'On récupère les éléments triés par position et on les assemble 
                For Each sLigne As DictionaryEntry In Liste
                    If sResultDoc <> "" Then sResultDoc &= vbCrLf
                    sResultDoc &= sLigne.Value
                Next
                'Ajustements par groupes
                If Me.CheckBoxGrouper.Checked Then
                    If Me.RadioButtonSubMatchCol.Checked Then sResultDoc = Commun.MettreEnColonnes(sResultDoc, "\|")
                    If Me.CheckBoxTrier.Checked Then sResultDoc = Commun.Trier(sResultDoc, vbCrLf)
                    If (sResultDoc <> "") Then sResultDoc = Indent(sResultDoc, 4)
                    DejaVu.Clear() 'Doublons par fichiers
                End If
                'Joindre les résultats courants au résultats globaux
                If sResultGlobal <> "" Then sResultGlobal &= vbCrLf
                sResultGlobal &= sResultDoc
                My.Application.DoEvents()
            End If
        Next 'Prochain fichier
        'Ajustements globaux
        If Not Me.CheckBoxGrouper.Checked Then
            If Me.RadioButtonSubMatchCol.Checked Then sResultGlobal = Commun.MettreEnColonnes(sResultGlobal, "\|")
            If Me.CheckBoxTrier.Checked Then sResultGlobal = Commun.Trier(sResultGlobal, vbCrLf)
            'If Me.CheckBoxDoublons.Checked And Not Me.RadioButtonModele.Checked Then sResultGlobal = Commun.SupprimerLignesDoubles(sResultGlobal)
        End If
        'Statistiques
        If Me.CheckBoxStat.Checked Then
            Call Form1.AfficherStatistiquesGlobales()
            sResultGlobal &= vbCrLf & vbCrLf & "STATISTIQUES:" & vbCrLf & vbCrLf
            sResultGlobal &= Commun.MettreEnColonnes(Form1.ExporterStatistiquesGlobales(), vbTab)
        End If
        Return sResultGlobal
    End Function

    Private Sub ButtonPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPreview.Click
        FormPreview.Text = "Extraction/Fusion"
        FormPreview.RichTextBox1.Text = Replace(Fusionner(), vbCrLf, vbLf)
        FormPreview.AppliquerMarqueurs()
        FormPreview.ShowDialog()
    End Sub

    Private Sub RadioButtonModele_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButtonModele.CheckedChanged
        Me.RichTextBox1.Enabled = Me.RadioButtonModele.Checked
        Me.ComboBoxModele.Enabled = Me.RadioButtonModele.Checked
        Me.Button4.Enabled = Me.RadioButtonModele.Checked
        Me.ButtonImporter.Enabled = Me.RadioButtonModele.Checked
        Me.CheckBoxTrier.Enabled = Not Me.RadioButtonModele.Checked
        If Not Me.CheckBoxTrier.Enabled Then Me.CheckBoxTrier.Checked = False
    End Sub

    Private Sub RadioButtonTexte_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButtonTexte.CheckedChanged
        Call AjusteModeles()
    End Sub

    Private Sub FormFusion_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Call Me.AjusteModeles()
    End Sub

    Private Sub ComboBoxModele_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBoxModele.SelectedIndexChanged
        If Me.RadioButtonRegEx.Checked Then
            Me.RichTextBox1.Text = Me.Modele
        ElseIf Me.RadioButtonTexte.Checked Then
            If Form1.ListViewMarqueurs.Items.ContainsKey(Me.ComboBoxModele.Text) Then
                Dim oMarqueur As ClassMarqueur = Form1.ListViewMarqueurs.Items(Me.ComboBoxModele.Text).Tag
                Me.RichTextBox1.Text = oMarqueur.Modele
            End If
        End If
    End Sub

    Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
        If Me.RadioButtonRegEx.Checked Then
            Me.Modele = Me.RichTextBox1.Text
        ElseIf Me.RadioButtonTexte.Checked Then
            If Form1.ListViewMarqueurs.Items.ContainsKey(Me.ComboBoxModele.Text) Then
                Dim oMarqueur As ClassMarqueur = Form1.ListViewMarqueurs.Items(Me.ComboBoxModele.Text).Tag
                oMarqueur.Modele = Me.RichTextBox1.Text
            End If
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        FormBrowser.WebBrowser1.DocumentText = My.Resources.SeparationHelp
        FormBrowser.Show()
    End Sub

    Private Sub ButtonImporter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonImporter.Click
        Me.OpenFileDialog1.Multiselect = False
        Me.OpenFileDialog1.Filter = "Tous|*.*"
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Try
                Me.RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(Me.OpenFileDialog1.FileName, System.Text.Encoding.Default)
            Catch Ex As Exception
                MsgBox("Erreur à la lecture du fichier " & Me.OpenFileDialog1.FileName & ": " & Ex.Message, MsgBoxStyle.Exclamation)
            End Try
        End If
    End Sub

  
    Private Sub Button12_Click(sender As System.Object, e As System.EventArgs) Handles Button12.Click
        FormRegEx.TextBoxRegEx.Text = Me.TextBoxRegEx.Text
        FormRegEx.RichTextBoxTest.Text = ""
        If FormRegEx.ShowDialog = DialogResult.OK Then
            Me.TextBoxRegEx.Text = FormRegEx.TextBoxRegEx.Text
        End If
    End Sub
End Class